package com.cup.wx.micro.web;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cup.common.response.ResponseCode;
import com.cup.common.response.ResponseData;
import com.cup.wx.micro.bean.AppletSession;
import com.cup.wx.micro.cache.SessionCache;
import com.cup.wx.micro.service.WXBaseService;
import com.cup.wx.micro.web.request.WxAppletRequest;

/**
 * Applet get user base info controller 
 * @author alan.deyu.zhao
 */
@RestController
@RequestMapping("/applet/usr")
public class AppletUserApi {
	
	@Autowired
	private WXBaseService wechatbaseService;
	
	/**
	 * applet user login
	 * get openid & sessionKey & unionId
	 * @throws Exception 
	 */
	@PostMapping("login")
	private String login(@RequestBody WxAppletRequest wxrequset) throws Exception{
		ResponseData<AppletSession> body = new ResponseData<>();
		AppletSession rs = wechatbaseService.appletLogin(wxrequset.getAppid(), 
				wxrequset.getSecret(), wxrequset.getCode());
		body.init(rs);
		return body.toString();
	}
	
	/**
	 * applet user encrypte userinfo 
	 */
	@PostMapping("info")
	private String info(@RequestBody WxAppletRequest wxrequset){
		ResponseData<Map<String, Object>> body = new ResponseData<>();
		
		AppletSession session = SessionCache.getIntance().get();
		if(session == null || session.getSessionKey() == null) {
			body.init(ResponseCode.FAIL, "基础信息不合法");
			return body.toResponse();
		}
		
		Map<String, Object> rs = wechatbaseService.getAppletUserInfo(wxrequset.getAppid(), 
				wxrequset.getEncryptedData(), 
				session.getSessionKey(), 
				wxrequset.getIv());
		body.init(rs);
		return body.toResponse();
	}
	
	/**
	 * applet user encrypte phone number 
	 */
	@PostMapping("phone")
	private String phone(@RequestBody WxAppletRequest wxrequset){
		
		ResponseData<Map<String, Object>> body = new ResponseData<>();
		
		AppletSession session = SessionCache.getIntance().get();
		if(session == null || session.getSessionKey() == null) {
			body.init(ResponseCode.FAIL, "基础信息不合法");
			return body.toResponse();
		}
		
		Map<String, Object> rs = wechatbaseService.getAppletPhoneNum(wxrequset.getAppid(), 
				wxrequset.getEncryptedData(), 
				session.getSessionKey(), 
				wxrequset.getIv());
		body.init(rs);
		return body.toString();
	}
}
